require('../css/mine.less')

document.ready(function () {

    //底部导航
    window.utils.addTab(2);

    // 判断用户是否登录，若没登陆，跳转到登录页
    window.utils.checkUserLogin();

    //获取节点
    let imgUploadIpt = document.querySelector("#imgUploadIpt"); //文件上传
    let portrait = document.querySelector("#portrait"); //头像按钮
    let times = document.querySelector("#times"); //时间
    let calorie = document.querySelector("#calorie"); //卡路里
    let quitLogin = document.querySelector("#quitLogin"); //退出登录
    let sign = document.querySelector("#sign"); //签名
    let nickname = document.querySelector("#nickname"); //昵称


    //获取本地的数据
    let user = JSON.parse(localStorage.getItem('user'))
    console.log(user.userId);


    //点击图片触发input的点击事件
    portrait.addEventListener("click", function (e) {
        e.preventDefault(); //阻止浏览器的默认行为
        imgUploadIpt.click();
    })
    imgUploadIpt.addEventListener('change', function () {
        console.log(this.files);
        //获取图片的值
        let file = this.files[0]
        console.log(file);

        //发送ajax修改头像表面
        $updateFile('/users/upload', 'imgurl', file, function (res) {
            // console.log(res);
            if (res.status === 0) {
                console.log("发送成功", res);
                let imgUrl = `http://139.9.177.51:8099${res.data}`
                portrait.src = imgUrl

                //把拿到的头像存到数据库
                $http.post('/users/userEdit', {
                    "userId": user.userId,
                    "imgurl": imgUrl
                }, function (res) {
                    if (res.status === 0) {
                        console.log("res>>>>>>", res);

                    }
                })
            }
        })

    })
    //渲染头像
    $http.get(`/users/accountinfo?userId=${user.userId}`, function (res) {
        if (res.status === 0) {
            //img不为空就渲染
            if(res.data.imgurl){
                portrait.src = res.data.imgurl
            }
        }
    })

    //渲染运动数据
    $http.get(`/users/mysportsBadge?userId=${user.userId}`, function (res) {
        if (res.status === 0) {
            console.log(res.data);
            times.textContent = Math.floor(res.data.sports.times);
            calorie.textContent = Math.floor(res.data.sports.calorie);
            if(res.data.user.sign){
                sign.textContent=res.data.user.sign;
            }
            nickname.textContent=res.data.user.nickname
        }
    })


    //退出登录
    quitLogin.addEventListener('click', function () {

        localStorage.clear();
        window.utils.toast("tick", '退出成功')
        window.setTimeout(function () {
            location.href = './login.html'
        }, 2000)
    })






})